package com.meatball.dronefly.fly;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;

import com.meatball.dronefly.MainActivity;
import com.meatball.dronefly.R;
import com.meatball.dronefly.service.WebSocketClientService;
import com.meatball.dronefly.utils.MWebSocketClient;

import java.util.Objects;

import dji.sdk.camera.VideoFeeder;
import dji.sdk.codec.DJICodecManager;

/**
 * 飞行界面
 * @author 张翔宇
 * @since 2022年9月8日
 */
public class FlyActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * FPV显示区域
     */
    private TextureView textureViewFPV;
    /**
     * 返回按钮
     */
    private Button buttonBack;
    /**
     * 编码译码器
     */
    private DJICodecManager djiCodecManager;
    /**
     * VideoFeeder视频流数据监听器
     */
    private VideoFeeder.VideoDataListener videoDataListener;

    private WebSocketClientService.WebSocketClientBinder binder;
    private WebSocketClientService jWebSClientService;
    private MWebSocketClient client;
    private ChatMessageReceiver chatMessageReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fly);
        // 启动服务
        startJWebSClientService();
        // 绑定服务
        bindService();
        // 注册广播
        doRegisterReceiver();
        //
        initUI();
        initListener();

    }

    /**
     * 初始化UI界面
     */
    private void initUI() {
        textureViewFPV = findViewById(R.id.texture_fly_fpv);
        buttonBack = findViewById(R.id.btn_fly_back);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        // textureViewFPV.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
        //     @Override
        //     public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surfaceTexture, int width, int height) {
        //         // 在SurfaceTexture可用时创建解码译码器
        //         if (Objects.isNull(djiCodecManager)) {
        //             djiCodecManager = new DJICodecManager(FlyActivity.this, surfaceTexture, width, height);
        //         }
        //     }
        //
        //     @Override
        //     public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surfaceTexture, int width, int height) {
        //
        //     }
        //
        //     @Override
        //     public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
        //         // 在SurfaceTexture销毁时释放编码译码器
        //         if (Objects.nonNull(djiCodecManager)) {
        //             djiCodecManager.cleanSurface();
        //             djiCodecManager = null;
        //         }
        //         return false;
        //     }
        //
        //     @Override
        //     public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surfaceTexture) {
        //
        //     }
        // });

        // 为返回按钮添加监听器
        buttonBack.setOnClickListener(this);

        // 为VideoFeeder视频流数据设置监听
        // videoDataListener = (bytes, i) -> {
        //     if (Objects.nonNull(djiCodecManager)) {
        //         djiCodecManager.sendDataToDecoder(bytes, i);
        //     }
        // };
        // VideoFeeder.getInstance().getPrimaryVideoFeed().addVideoDataListener(videoDataListener);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_fly_back) {
            back();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeListener();
        //
        unRegisterReceiver();
        unbindService(serviceConnection);
    }

    /**
     * 返回主界面
     */
    private void back() {
        this.finish();
    }

    /**
     * 一处视频监听器
     */
    private void removeListener() {
        // 移除在VideoFeed的视频流数据监听器
        VideoFeeder.getInstance().getPrimaryVideoFeed().removeVideoDataListener(videoDataListener);
    }

    /**
     * 动态广播接收消息
     */
    private String TAG="JWebSocketClientService";
    private class ChatMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            Log.e(TAG, "-----接收服务端数据：" + message);
        }
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.meatball.dronefly.servicecallback.content");
        registerReceiver(chatMessageReceiver, filter);
    }

    /**
     * 注销广播
     */
    private void unRegisterReceiver() {
        unregisterReceiver(chatMessageReceiver);
    }

    /**
     * 启动服务（websocket客户端服务）
     */
    private void startJWebSClientService() {
        Intent intent = new Intent(this, WebSocketClientService.class);
        startService(intent);
    }
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            // 服务与活动成功绑定
            Log.e(TAG, "服务与活动成功绑定");
            binder = (WebSocketClientService.WebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 服务与活动断开
            Log.e(TAG, "服务与活动成功断开");
        }
    };

    private void bindService() {
        Intent intent = new Intent(FlyActivity.this, WebSocketClientService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }
}